﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Forms;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Definitions;
using FlaUI.Core.Input;
using FlaUI.Core.WindowsAPI;
using FlaUI.UIA3;
using QQTools.Core.Enums.SendGroupMessage;
using QQTools.Data.Enums.SendGroupMessage;
using QQTools.Data.Models.SendGroupMsg;
using QQTools.Data.Plus;
using QQTools.Logging;
using QQTools.Utils;
using static System.Net.Mime.MediaTypeNames;


namespace QQTools.Services.Automation
{
    public class SendGroupMsgAuto
    {
        /// <summary>
        /// QQ进程 ID
        /// </summary>
        protected int _pid;
        /// <summary>
        /// QQ主窗口句柄
        /// </summary>
        protected IntPtr _qqMainWindowHandle;

        public SendGroupMsgAuto(int pid)
        {
            _pid = pid;
            // 获取 QQ 主窗口句柄
            _qqMainWindowHandle = Win32Api.GetWindowHandle(pid, "QQ", "TXGuiFoundation", false);
        }


        public async Task<(SendGroupMsgResult Result, int Index)> SendGroupMsg(string qq, string groupNumber, GroupMsgModel groupMsgModel, CancellationToken token, int attempt = 1)
        {

            if (string.IsNullOrEmpty(qq))
            {
                LogManager.Error($"[SendGroupMsg] QQ号不能为空");
                return (SendGroupMsgResult.InvalidQQ, -1);
            }
            if (string.IsNullOrEmpty(groupNumber))
            {
                LogManager.Error($"[SendGroupMsg] 群号不能为空");
                return (SendGroupMsgResult.InvalidGroupNumber, -1);
            }

            // 当前发送资源的索引
            int index = 0;
            try
            {
                // 1.先清理窗口, 避免影任务
                //InitCleanWindow();
                // 1.1隐藏其他QQ窗口
                Win32Api.HideAllWindowsExcept("QQ", "TXGuiFoundation", _qqMainWindowHandle);

                // 2.调出群聊窗口
                // 2.1生成腾讯URL
                LogManager.Info($"[SendGroupMsg] 指令发送：打开QQ: {qq} 的群：{groupNumber}");
                string url = QQPlus.GenerateTencentUrl(groupUin: Convert.ToInt64(groupNumber), qqUin: qq);
                // 2.2 打开群聊窗口
                Process.Start(url);
                LogManager.Info($"[SendGroupMsg] 指令发送完毕：QQ: {qq} 的群：{groupNumber}");
                await Task.Delay(1000);
                // 3. 获取群聊窗口
                //int processId = QQPlus.GetQQPid(qq);
                Win32Api.GetWindowThreadProcessId(_qqMainWindowHandle, out int processId);
                AutomationElement groupChatWindow = null;

                for (int i = 0; i < 5; i++)
                {
                    groupChatWindow = await QQPlus.GetGroupChatWindowWin32(processId);
                    if (groupChatWindow != null)
                    {
                        break;
                    }
                    await Task.Delay(200, token);
                }

                if (groupChatWindow == null)
                {
                    // 检查是否存在安全提醒窗口或添加群窗口
                    if (QQPlus.CheckAndHandleSpecialWindows())
                    {
                        LogManager.Error("[SendGroupMsg] 出现安全提醒窗口或添加群窗口");
                        return (SendGroupMsgResult.GroupBlockedOrNotAdded, -1);
                    }

                    // 检查是否离线
                    if (QQPlus.CheckQQIsOffline(qq) == false)
                    {
                        LogManager.Error($"[SendGroupMsg] QQ:{qq} 已离线");
                        return (SendGroupMsgResult.QQOffline, -1);
                    }

                    LogManager.Error("[SendGroupMsg] 获取群聊窗口失败");
                    return (SendGroupMsgResult.GroupNotFound, -1);
                }

                LogManager.Info($"[SendGroupMsg] 成功打开群聊:{groupChatWindow?.Name}");
                // 设置群聊窗口为前台窗口
                Win32Api.SetForegroundWindow(groupChatWindow.Properties.NativeWindowHandle);

                await Task.Delay(1000);

                var editControl = groupChatWindow.FindFirstDescendant(cf =>
                       cf.ByControlType(FlaUI.Core.Definitions.ControlType.Edit)
                       .And(cf.ByName("输入"))
                   );
                if (editControl == null)
                {
                    LogManager.Error("[SendGroupMsg] 找不到群聊输入框");
                    // 检查是否禁言

                    AutomationElement muteStatusText = groupChatWindow.FindFirstDescendant(cf =>
                       cf.ByControlType(FlaUI.Core.Definitions.ControlType.Text)
                       .And(cf.ByName("全员禁言中，只允许群主和管理员发言"))
                    );
                    if (muteStatusText != null)
                    {
                        // 关闭群聊窗口
                        FlauiAuto.CloseWindow(groupChatWindow);
                        LogManager.Info("[SendGroupMsg] 群聊窗口被禁言");
                        return (SendGroupMsgResult.GroupMute, -1);
                    }
                    else
                    {
                        // 关闭群聊窗口
                        FlauiAuto.CloseWindow(groupChatWindow);
                        LogManager.Error("[SendGroupMsg] 找不到群聊窗口");
                        return (SendGroupMsgResult.GroupNotFound, -1);
                    }
                }
                else
                {
                    LogManager.Info("[SendGroupMsg] 找到输入框");
                    await Task.Delay(500);
                    editControl.Click();
                    await Task.Delay(100);
                    // 清除并输入
                    // FlauiAuto.ClearAndSendKeys(editControl, "你好");

                    index = await SendGroupMsgHandle(groupChatWindow, editControl, groupMsgModel, token);
                    // 关闭群聊窗口, 需要检查 是否出现 文件对话框窗口
                    var fileDialogWindow = groupChatWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Window)
                        .And(cf.ByName("打开"))
                    );
                    if (fileDialogWindow != null)
                    {
                        // 文件对话框窗口
                        LogManager.Info($"[SendGroupMsg] 文件对话框窗口还存在, ->关闭窗口");
                        FlauiAuto.CloseWindow(fileDialogWindow);
                        await Task.Delay(1000, token);
                    }

                    FlauiAuto.CloseWindow(groupChatWindow);
                    LogManager.Info($"[SendGroupMsg] 发送成功");
                    return (SendGroupMsgResult.Success, index);
                }
            }
            catch (Exception ex)
            {
                LogManager.Info($"[SendGroupMsg] 第 {attempt} 次尝试失败: {ex.Message}", ex);
            }
            return (SendGroupMsgResult.Unknown, index); // 任务失败
        }



        /// <summary>
        /// 初始化干净的窗口
        /// </summary>
        /// <returns></returns>
        public void InitCleanWindow()
        {
            LogManager.Info($"[InitCleanWindow] 开始初始化干净的窗口");
            try
            {

                Win32Api.CloseAllWindows("TXGuiFoundation", "安全提醒");
                // 关闭 转发窗口
                //Win32Api.CloseAllWindows("TXGuiFoundation", "转发");
                // 群公告窗口
                //Win32Api.CloseAllWindows("TXGuiFoundation", "");
                // 关闭 我的收藏窗口
                //Win32Api.CloseAllWindowsEndsWith("TXGuiFoundation", "的 收藏");
                //Win32Api.CloseAllWindowsEndsWith("TXGuiFoundation", "个会话");
                Win32Api.CloseAllQQWindowsEndsWith("个会话");
                LogManager.Info($"[InitCleanWindow] 完成初始化干净的窗口");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[InitCleanWindow] 初始化干净的窗口发生错误: {ex.Message}");
            }
        }


        public async Task<int> SendGroupMsgHandle(AutomationElement groupChatWindow, AutomationElement editControl, GroupMsgModel groupMsgModel, CancellationToken token)
        {
            int index = -1;
            if (editControl == null)
            {
                LogManager.Error("[SendGroupMsgHandle] 找不到输入框控件");
                return index;
            }

            switch (groupMsgModel.MsgType)
            {
                case SendGroupMsgType.文字:
                    // 发送文本消息
                    LogManager.Info($"[SendGroupMsgHandle] 发送文本消息: {groupMsgModel.Text}");
                    break;
                case SendGroupMsgType.图片:
                    // 发送图片消息
                    LogManager.Info($"[SendGroupMsgHandle] 发送图片消息: {groupMsgModel.PicPath}");
                    index = await SendPicture(groupChatWindow, editControl, groupMsgModel.PicPath, token);
                    break;
                case SendGroupMsgType.文件:
                    // 发送视频消息
                    break;
                default:
                    LogManager.Error($"[SendGroupMsgHandle] 不支持的消息类型: {groupMsgModel.MsgType}");
                    break;
            }
            return index;
        }


        internal async void Test()
        {
            using (var automation = new UIA3Automation())
            {

                int processId = QQPlus.GetQQPid("3989236730");
                AutomationElement groupChatWindow = null;
                try
                {
                    for (int i = 0; i < 5; i++)
                    {
                        groupChatWindow = await QQPlus.GetGroupChatWindowWin32(processId);
                        if (groupChatWindow != null)
                        {
                            break;
                        }
                        await Task.Delay(200);
                    }
                }
                catch (Exception)
                {
                    LogManager.Error("[SendGroupMsg] 出现安全提醒窗口或添加群窗口");
                    throw;
                }


                if (groupChatWindow != null)
                {

                    var editControl = groupChatWindow.FindFirstDescendant(cf =>
                        cf.ByControlType(FlaUI.Core.Definitions.ControlType.Edit)
                        .And(cf.ByName("输入"))
                    );
                    if (editControl != null)
                    {
                        editControl.Click();
                        await Task.Delay(1000);
                        // 清除并输入
                        // FlauiAuto.ClearAndSendKeys(editControl, "你好");

                        //  await SendPicture(groupChatWindow, editControl, "C:\\Users\\12392\\Desktop\\QQTools图库", null);

                        LogManager.Info($"[Test] 成功找到群聊窗口: ");
                    }
                    else
                    {
                        LogManager.Error("[Test] 找不到群聊窗口");
                    }
                }
            }
        }

        public async Task<int> SendPicture(AutomationElement groupChatWindow, AutomationElement editControl, string filePath, CancellationToken token)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                LogManager.Error($"[SendPicture] 图片路径不能为空");
                return -1;
            }
            if (!System.IO.Directory.Exists(filePath))
            {
                LogManager.Error($"[SendPicture] 图片目录不存在: {filePath}");
                return -1;
            }
            if (editControl == null)
            {
                LogManager.Error("[SendPicture] 找不到编辑控件");
                return -1;
            }
            try
            {
                // 获取目录中的所有图片文件
                string[] imageFiles = Directory.GetFiles(filePath, "*.*", System.IO.SearchOption.TopDirectoryOnly)
                .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png") || s.EndsWith(".jpeg")).ToArray();
                if (imageFiles.Length == 0)
                {
                    LogManager.Error($"[SendPicture] 目录中没有图片文件");
                    return -1;
                }

                // 随机选择一张图片
                Random random = new Random();
                int index = random.Next(0, imageFiles.Length);
                string selectedImage = imageFiles[index];
                // 发送图片, 使用复制粘贴
                // 1. 复制图片到剪贴板

                // 1. 检查文件是否存在
                if (!File.Exists(selectedImage))
                {
                    LogManager.Info($"[SendPicture] 图片文件不存在：{selectedImage}");
                    return -1;
                }
                LogManager.Info($"[SendPicture] 随机图片：{selectedImage}");
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[SendPicture] 取消发送图片");
                    return -1;
                }
                ClickControl(groupChatWindow, editControl);
                await Task.Delay(500);
                // 清除并输入
                // 假设你已经 focus 了控件
                Keyboard.TypeSimultaneously(VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_A); // Ctrl+A选中所有文本
                await Task.Delay(50);
                //Keyboard.TypeSimultaneously(VirtualKeyShort.DELETE); // 删除
                bool ret = await SendPictureByDialog(groupChatWindow, selectedImage, token);
                await Task.Delay(1000);

                AutomationElement sendButton = groupChatWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Button)
                    .And(cf.ByName("发送(&S)"))
                );
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[SendPicture] 取消发送图片");
                    return -1;
                }
                if (sendButton == null)
                {
                    LogManager.Info($"[SendPicture] Alt+S 发送图片：{selectedImage}");
                    Keyboard.TypeSimultaneously(VirtualKeyShort.ALT, VirtualKeyShort.KEY_S); // Alt+S
                }
                else
                {
                    LogManager.Info($"[SendPicture] 点击按钮发送图片：{selectedImage}");
                    ClickControl(groupChatWindow, sendButton);
                }
                await Task.Delay(2000);
                LogManager.Info($"[SendPicture] 成功发送图片: {selectedImage}");
                return index;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[SendPicture] 操作异常：{ex.Message}");
                return -1;
            }

        }

        public void ClickControl(AutomationElement mainWindow, AutomationElement control)
        {
            if (control == null || mainWindow == null)
            {
                LogManager.Error("[ClickControl] 找不到控件");
                return;
            }
            try
            {
                // 获取窗口和控件的坐标信息
                //var windowRect = mainWindow.BoundingRectangle;
                //var controlRect = control.BoundingRectangle;
                //// 计算相对位置
                //int relativeX = (int)(controlRect.Left - windowRect.Left);
                //int relativeY = (int)(controlRect.Top - windowRect.Top);
                //// 后台鼠标点击
                //Win32Api.SendClick(mainWindow.Properties.NativeWindowHandle, relativeX, relativeY);

                //// 前台鼠标点击
                System.Drawing.Point point = default;
                // 获取sendButton的中心坐标
                var rect = control.BoundingRectangle;
                point.X = rect.X + rect.Width / 2;
                point.Y = rect.Y + rect.Height / 2;
                Mouse.Click(point);

            }
            catch (Exception ex)
            {
                control.Click();
                LogManager.Error($"点击控件发生异常, 原因：{ex.Message}", ex);
            }
        }

        public void SendPictureByClipboard(AutomationElement editControl, string filePath)
        {
            // 保存当前剪贴板内容
            var previousClipboardContent = Utils.Utils.GetClipboardContent();
            Utils.Utils.CopyImageToClipboard(filePath);
            SendKeys.SendWait("^v"); // Ctrl+V粘贴
            // 4. 使用完剪贴板的图片后还原之前的剪贴板内容
            Utils.Utils.RestoreClipboardContent(previousClipboardContent);
        }

        public async Task<bool> SendPictureByDialog(AutomationElement groupWindow, string filePath, CancellationToken token)
        {
            if (groupWindow == null)
            {
                LogManager.Error("[SendPictureByDialog] 找不到群聊窗口");
                return false;
            }

            if (!File.Exists(filePath))
            {
                LogManager.Error($"[SendPictureByDialog] 文件路径无效：{filePath}");
                return false;
            }
            try
            {
                AutomationElement sendPictureButton = groupWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Button)
                    .And(cf.ByName("发送图片"))
                );
                if (sendPictureButton == null)
                {
                    LogManager.Error("[SendPictureByDialog] 找不到发送图片按钮");
                    return false;
                }
                sendPictureButton.Click();
                await Task.Delay(1000);
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[SendPictureByDialog] 取消发送图片");
                    return false;
                }
                AutomationElement automationElement = groupWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Edit)
                    .And(cf.ByName("文件名(N):"))
                );
                if (automationElement != null)
                {
                    // 记录几次找不到 打开 按钮
                    int count = 0;
                    while (true)
                    {
                        if (token.IsCancellationRequested)
                        {
                            LogManager.Info("[SendPictureByDialog] 取消发送图片");
                            return false;
                        }

                        var openBtn = groupWindow.FindFirstDescendant(cf => cf.ByName("打开(O)").And(cf.ByControlType(ControlType.Button))); // 点击打开按钮
                        if (openBtn != null)
                        {
                            await Task.Delay(500, token);
                            //Keyboard.TypeSimultaneously(VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_A); // Ctrl+A选中所有文本
                            //await Task.Delay(50);
                            //Keyboard.TypeSimultaneously(VirtualKeyShort.DELETE); // 删除
                            //                                                     //automationElement?.AsTextBox().Enter(filePath);

                            var textBox = automationElement?.AsTextBox();
                            await Task.Delay(2000, token);
                            textBox.Focus(); // 获取焦点
                            ClickControl(groupWindow, textBox);
                            await Task.Delay(1000, token);
                            ClickControl(groupWindow, textBox);
                            // textBox.Text = filePath; // 输入文件路径
                            // Keyboard.Type(filePath);
                            await Task.Delay(1000, token);
                            IntPtr hWnd = textBox.Properties.NativeWindowHandle.ValueOrDefault;
                            if (hWnd != IntPtr.Zero)
                            {
                                Win32Api.SendMessage(hWnd, Win32Api.WM_SETTEXT, IntPtr.Zero, filePath);
                            }
                            else
                            {
                                textBox.Enter(filePath);
                            }

                            await Task.Delay(1000, token);
                            LogManager.Info($"[SendPictureByDialog] 输入图片地址：{filePath}");
                            ClickControl(groupWindow, openBtn);
                            await Task.Delay(1000, token);
                        }
                        else
                        {
                            count++;
                            if (count >= 3)
                            {
                                // 打开文件对话框的窗口
                                var openWindow = groupWindow.FindFirstDescendant(cf => cf.ByName("打开").And(cf.ByControlType(ControlType.Window)));
                                if (openWindow == null)
                                {

                                    LogManager.Info($"[SendPictureByDialog] 图片地址输入完毕!");
                                    break;

                                }
                                LogManager.Info($"[SendPictureByDialog] 还在输入图片地址中");
                            }
                        }
                        await Task.Delay(1000, token);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[SendPictureByDialog] 操作异常：{ex.Message}");
                return false;
            }
            return false;
        }

    }
}
